<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>地图选择器</title>
    <link href="../css/global.css" rel="stylesheet" type="text/css">
    <link href="all/mapSelector.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="main">
        <div class="mtr">
            <div class="one none">
                <div class="header">
                    <span>地址选择</span>
                    <input id="searchText" type="text">
                    <div id="searchResultPanel"></div>
                    <img src="all/search.png" height="16" width="16">
                </div>
                <div id="container" class="vessel"></div>
                <div class="btnBox">
                    <div class="tip">
                        <span class="none">请填写详细地址</span>
                        <input type="text">
                    </div>
                    <div class="fr">
                        <button class="btn btn-submit editAdd">确定</button>
                        <button class="btn btn-return return">返回</button>
                    </div>
                </div>
            </div>
            <div class="content two">
                <div class="address-list">
                </div>
                <div class="noaddress none">
                    <img src="all/noaddress.png">
                    <p>尚未添加地址</p>
                </div>
                <div class="btnBox">
                    <div class="fr">
                        <button class="btn btn-submit addAdds">新增地址</button>
                        <button class="btn btn-return cancel">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="../jquery-1.11.1.min.js"></script>
    <script src="../config.js"></script>
    <script src="../sy_main.js"></script>
    <script src="../gps.js"></script>
    <script src="../jquery.nicescroll/jquery.nicescroll.min.js"></script>
    <script src="https://api.map.baidu.com/api?v=2.0&ak=6NSf3ER1QWCV8HuCIDVVwLrslmRHjD65&s=1&services=&t=20171031174121"></script>
    <script type="text/javascript">
        $(".address-list").niceScroll({
            cursorcolor: "#d9d9d9",
            cursorwidth: "5px",
            cursorborderradius: 0,
            cursorborder: 0
        });
        // 获取组织code
        var orgInfo = JSON.parse(window.localStorage.getItem("backstage-access-currentOrgInfo"));
        var orgcode = '';
        if(orgInfo && orgInfo.orgCode) {
            orgcode = orgInfo.orgCode;
        } 
        var map = new BMap.Map("container",{enableMapClick:false});          // 创建地图实例
        var point = new BMap.Point(106.53063501,29.54460611);  // 创建点坐标
        var geoc = new BMap.Geocoder();               // 创建地理编码实例 
        var infoFlag = '';                            //详细地址
        var marker = new BMap.Marker(point),nowPoint = point;          //地图地点标记和经纬度
        map.centerAndZoom(point, 15);                 // 初始化地图，设置中心点坐标和地图级别
        map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
        map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用

        // 传出数据
        var comeOut = {
            address: infoFlag,
            lng: nowPoint.lng,
            lat: nowPoint.lat
        };
        initPage();
        var ac = new BMap.Autocomplete({    //建立一个自动完成的对象
            "input" : "searchText",
            "location" : map
        });

        ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if (e.fromitem.index > -1) {
                value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }    
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
        
            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }    
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            $("#searchResultPanel").innerHTML = str;
        });
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                var mk = new BMap.Marker(r.point);
                map.addOverlay(mk);
                map.panTo(r.point);
            }
        })
        var myValue;
        ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            infoFlag = myValue;
            $("#searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
        
            setPlace();
        });

        function setPlace(){
            map.clearOverlays();    //清除地图上所有覆盖物
            function myFun(){
                // nowPoint = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                // map.centerAndZoom(nowPoint, 15);
                // marker = new BMap.Marker(nowPoint);
                // comeOut.address = infoFlag;
                // comeOut.lng = nowPoint.lng;
                // comeOut.lat = nowPoint.lat;
                // $(".tip input").val(infoFlag);
                // map.addOverlay(marker);    //添加标注
                // // marker.enableDragging();
                nowPoint = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                map.centerAndZoom(nowPoint, 15);
                marker = new BMap.Marker(nowPoint);
                var bdtogd = GPS.bd_encrypt(jsonData.lat,jsonData.lng)
                comeOut.address = infoFlag;
                comeOut.lng = bdtogd.lon;
                comeOut.lat = bdtogd.lat;
                parent.$('.singleMapSelector-iframe').data('outInfo', JSON.stringify(comeOut));
                $(".tip input").val(infoFlag);
                map.addOverlay(marker);    //添加标注
            }
            var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
            });
            local.search(myValue);
        }

        // 设置标注
        function addMarker(point){
            map.clearOverlays();
            marker = new BMap.Marker(point);
            map.addOverlay(marker);
            // marker.enableDragging();
        }

        //单击获取点击的经纬度
        map.addEventListener("click",function(e){
            if(e.overlay){
                var infoWindow = new BMap.InfoWindow(infoFlag, {width: 200,height: 50});
                map.openInfoWindow(infoWindow,nowPoint);
            }else{
                nowPoint = new BMap.Point(e.point.lng,e.point.lat);
                geoc.getLocation(e.point, function(rs){
                    var addComp = rs.addressComponents;
                    infoFlag = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    var bdtogd =  GPS.bd_decrypt(nowPoint.lng,nowPoint.lat);
                    comeOut.address = infoFlag;
                    comeOut.lng = bdtogd.lon;
                    comeOut.lat = bdtogd.lat;
                    parent.$('.singleMapSelector-iframe').data('outInfo', JSON.stringify(comeOut));
                    $(".tip input").val(infoFlag);
                    addMarker(nowPoint);
                });  
            }
                   
        });

        $('.btnBox').on('click', '.editAdd', function(){
            if(!infoFlag) {
                sy.toast('您尚未选择地址');
                return;
            }
            $(".tip input").animate({width:"310px",paddingLeft:"10px",paddingRight:"10px"},200);
            setTimeout("$('.tip span').removeClass('none');$('.tip input').show();$('.one .btn-submit').removeClass('editAdd').addClass('submit');",300);
            
        });

        $('.btnBox').on('click', '.submit', function(){
            comeOut.address = $.trim($(".tip input").val());
            post(site.apiUrl + '/orgFrequentlyAddress/insertAddr', {addrName:comeOut.address,latitude:comeOut.lat,longitude:comeOut.lng,orgCode:orgcode}, function(data) {
                if(data.code == 'rest.success') {
                    initPage();
                    $('.return').click();
                } else {
                    ly.toast('新增失败');
                }
            });
        });

        $('.return').click(function() {
            $('.one').toggleClass('none').siblings('.two').toggleClass('none');
            $(".tip input").animate({width:"0px",paddingLeft:"0px",paddingRight:"0px"},10);
            $('.tip span').addClass('none');
            $('.one .btn-submit').addClass('editAdd').removeClass('submit');
            infoFlag = '';
            $('#searchText').val('');
            marker = new BMap.Marker(point);
            nowPoint = point;
            map.clearOverlays();
        });

        $('.addAdds').click(function(){
            $('.one').toggleClass('none').siblings('.two').toggleClass('none');
        });

        $('.address-list').on('click', '.del', function(){
            var $thisDiv = $(this).parent().parent();
            post(site.apiUrl + '/orgFrequentlyAddress/deleteAddr', {id:$thisDiv.attr('aid')}, function(data) {
                if(data.code == 'rest.success') {
                    $thisDiv.remove();
                    if($('.address-list>div').length == 0) {
                        $('.address-list').addClass('none').siblings('.noaddress').removeClass('none');
                    }
                    $(".address-list").getNiceScroll().resize();
                } else {
                    sy.toast('删除失败');
                }
            });
        });

        //初始化或更新页面
        function initPage() {
            //调用添加地址接口
            post(site.apiUrl + '/orgFrequentlyAddress/selectListByOrgCode', {orgCode:orgcode}, function(data) {
                // console.log(data);
                if(data.code == "rest.success") {
                    if(data.result.length == 0) {
                        $('.address-list').addClass('none').siblings('.noaddress').removeClass('none');
                    } else {
                        $('.address-list').removeClass('none').siblings('.noaddress').addClass('none');
                        $('.address-list').html('');
                        $.each(data.result, function(i, item) {
                            $('.address-list').append('<div aid="'+ item.id +'"><i class="iconfont icon-dingwei"></i><div class="every-list">'+
                                '<span>'+ item.addrName +'</span><p class="f14">经度：<label>'+ item.longitude +'</label>'+
                                '&nbsp;&nbsp;&nbsp;纬度：<label>'+ item.latitude +'</label></p><i class="iconfont icon-cha del"></i></div></div>');
                        });
                        $(".address-list").getNiceScroll().resize();
                    }
                } else {
                    // sy.toast('数据获取错误');
                }
            });
        }

    </script>
</body>

</html>
